﻿
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System.IdentityModel.Tokens.Jwt;
using tju.cme.BookStore2024.webapi.Models.Tools;
using tju.cme.BookStore2024.webapi.Models.ViewModels.Reader;
using tju.cme.BookStore2024.webapi.Services;

namespace tju.cme.BookStore2024.webapi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ReaderController(ILogger<ReaderController> logger,ReaderServices services): ControllerBase
    {
        /// <summary>
        /// 获得所有读者账户信息
        /// </summary>
        /// <returns></returns>
        [HttpGet("GetAll")]
        public async Task<IActionResult> GetAll()
        {
            return Ok(new ReturnMessage(await services.GetAllReadersAsync()));
        }

        /// <summary>
        /// 检查用户名是否被使用过
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        [HttpGet("isUserNameUsed/{name}")]
        public async Task<IActionResult> IsNameUsed([FromRoute] string name)
        {
            return Ok(new ReturnMessage(await services.IsUserNameUsedAsync(name)));
        }

        /// <summary>
        /// 读者注册
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost("Register")]
        public async Task<IActionResult> Register([FromBody] ReaderRegisterModel model)
        {
            await services.ReaderRegisterAsync(model);
            logger.LogInformation($"{model.UserName}注册成功");
            return Ok(new ReturnMessage(string.Empty));
        }

        /// <summary>
        /// 读者登录 
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost("Login")]
        public async Task<IActionResult> Login(ReaderLoginModel model)
        {
            var token = await services.VerificationAsync(model);
            logger.LogInformation($"{model.UserName}登录成功");
            return Ok(new ReturnMessage(new JwtSecurityTokenHandler().WriteToken(token)));
        }
    }
}
